/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.stakeholder;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import session.stateless.StakeholderSessionBeanStateless;
import exception.ExistException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedProperty;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import util.entityhelper.StakeholderAccountState;

/**
 *
 * @author jamie
 */
@ManagedBean(name = "stakeholderPortalManagedBean")
@ViewScoped
public class AddStakeholderPortalInfoManagedBean implements Serializable {

    @EJB
    private StakeholderSessionBeanStateless stakeholderPortalMgt;
    //@EJB
    //private SystemMessagesRemote systemMessages;
    
    private String userName;
    private Long stakeholderID;
    private String stakeholderDesc;
   
    private String imgUrl;
    
    private StakeholderAccountState stakeholderAccountState;
    
    
    //private MediaUploadManagedBean uploadBean;
    
    private boolean success = false;
    private String nextPage;
    private FacesContext ctx = FacesContext.getCurrentInstance();

    public void initView(PhaseEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        FacesContext.getCurrentInstance().getExternalContext().getFlash().clear();
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        
        stakeholderID = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderId");
        if (stakeholderID == null) {
            
            System.out.println("enter stakeholderID = null? ");
            nextPage = (ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().getActionURL(ctx, "/StakeholderLogin.xhtml")));
            try {
                ctx.getExternalContext().redirect(nextPage);
            } catch (IOException ioe) {
                ioe.printStackTrace();

            }
        }
        else {
             if (stakeholderAccountState == null) {
                try {

                    stakeholderAccountState = stakeholderPortalMgt.getStakeholderPortalInfoById(stakeholderID);
                    System.out.println("userId at PortalBean " + stakeholderID);
                    System.out.println("imageURL " +stakeholderAccountState.getImgUrl());
                   
                    if(stakeholderAccountState.getImgUrl()== null){
                      stakeholderAccountState.setImgUrl("/images/upload/in_room_dining_img.jpg");
                    }
                    //System.out.println("mediaBean " +uploadBean.getImageFilePath());
                    
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        
    }

    public void handleImageUpload(FileUploadEvent event) throws AbortProcessingException, NoSuchAlgorithmException
    {
        
        try
        {           
            String filePath =  
                    FacesContext.getCurrentInstance().getExternalContext().getRealPath("images/upload");
            System.out.println("filePath is: "+filePath);
            File result = new File(filePath + System.getProperty("file.separator") + event.getFile().getFileName());
            FileOutputStream out = new FileOutputStream(result);

            int a;
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];

            InputStream is = event.getFile().getInputstream();

            while (true)
            {
                a = is.read(buffer);

                if (a < 0)
                {
                    break;
                }

                out.write(buffer, 0, a);
                out.flush();
            }

            out.close();
            is.close();

            imgUrl = "/images/upload/" + event.getFile().getFileName();
            stakeholderAccountState.setImgUrl(imgUrl);
            System.out.println("imagefilepath: " + imgUrl);
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            //FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("imageFilePath", imageFilePath);
            stakeholderAccountState.setImgUrl(imgUrl);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("stakeholderId", stakeholderID);

        }
        catch (IOException e)
        {
             FacesContext.getCurrentInstance().addMessage("sPortalform", new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
            e.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
    public void saveStakeholderPortalInfo(ActionEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //stakeholderAccountState.setStakeholderDesc(stakeholderDesc);
        System.out.println("stakeholder saved description: " + stakeholderAccountState.getStakeholderDesc());
        String statusMessage = null;

        //stakeholderAccountState.setImgUrl((String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("imageFilePath"));

        System.out.println("what's the path of image " + imgUrl);
        //stakeholderAccountState.setImgUrl(bean.getImageFilePath());

        try {
            success = (stakeholderPortalMgt.addPortalInfoByInfo(stakeholderAccountState));
            System.out.println("success: " + isSuccess());
            //ctx.getExternalContext().getSessionMap().put("stakeholderAccountState", stakeholderAccountState);
            //System.out.println("Save StakeholderID" + ctx.getExternalContext().getSessionMap().get("staffAccountId"));
            if (isSuccess()) {
                statusMessage = "Stakeholder portal is updated successfully";
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, statusMessage));
                

            } else {
                statusMessage = "Stakeholder Portal data not saved.";
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, statusMessage));
            }
            //System.out.println("successful? " + statusMessage);
            // FacesMessage msg = new FacesMessage(statusMessage);
            //FacesContext.getCurrentInstance().addMessage(null, msg);
            //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));

        } catch (ExistException ex) {
            ex.printStackTrace();
        }

    }

    public void redirectPage(ActionEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException, IOException {
        
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("stakeholderAccState", stakeholderAccountState);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("stakeholderId", stakeholderID);
        FacesContext ctx = FacesContext.getCurrentInstance();
        nextPage = ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().getActionURL(ctx, "/stakeholder/PreviewPortal.xhtml"));

        ctx.getExternalContext().redirect(nextPage);
       

    }


    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @return the stakeholderID
     */
    public long getStakeholderID() {
        return stakeholderID;
    }

    /**
     * @return the stakeholderDesc
     */
    public String getStakeholderDesc() {
        return stakeholderDesc;
    }

    /**
     * @return the imgUrl
     */
    public String getImgUrl() {
        return imgUrl;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * @param stakeholderID the stakeholderID to set
     */
    public void setStakeholderID(long stakeholderID) {
        this.stakeholderID = stakeholderID;
    }

    /**
     * @param stakeholderDesc the stakeholderDesc to set
     */
    public void setStakeholderDesc(String stakeholderDesc) {
        this.stakeholderDesc = stakeholderDesc;
    }

    /**
     * @param imgUrl the imgUrl to set
     */
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    /**
     * @return the stakeholderAccountState
     */
    public StakeholderAccountState getStakeholderAccountState() {
        return stakeholderAccountState;
    }

    /**
     * @param stakeholderAccountState the stakeholderAccountState to set
     */
    public void setStakeholderAccountState(StakeholderAccountState stakeholderAccountState) {
        this.stakeholderAccountState = stakeholderAccountState;
    }

    /**
     * @return the success
     */
    public boolean isSuccess() {
        return success;
    }

    /**
     * @param success the success to set
     */
    public void setSuccess(boolean success) {
        this.success = success;
    }

    /**
     * @return the nextPage
     */
    public String getNextPage() {
        return nextPage;
    }

    /**
     * @param nextPage the nextPage to set
     */
    public void setNextPage(String nextPage) {
        this.nextPage = nextPage;
    }

   
}
